package com.wxb.quartz.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wxb.quartz.alipay.AlipayField;
import com.wxb.quartz.alipay.TradeStatusField;
import com.wxb.quartz.model.PayRecord;
import com.wxb.quartz.service.AlipayService;
import com.wxb.quartz.service.PayRecordService;
import com.wxb.quartz.util.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;

/**
 * describe:
 *
 * @author : 王校兵
 * @version : v1.0
 * @time : 2017/7/11  10:22
 */

@Component
@Configurable
@EnableScheduling
public class ScheduledTasks {

    @Autowired
    private PayRecordService payService;

    @Autowired
    private AlipayService alipayService;

    public void work() {
        //这儿插入具体的调度任务
        System.out.println("execute work " + System.currentTimeMillis());

        List<PayRecord> payRecordsList = payService.findWaitPayOrder();

        Iterator<PayRecord> iterator = payRecordsList.iterator();
        while (iterator.hasNext()) {
            PayRecord payRecord = iterator.next();

            String orderId = payRecord.getOrderId();

            String result = alipayService.orderQuery(orderId);

            JSONObject jsonResult = JSON.parseObject(result);

            JSONObject alipay_trade_query_response = jsonResult.getJSONObject("alipay_trade_query_response");

            String code = alipay_trade_query_response.getString("code");
            //网管返回值为成功
            if (null != code && "10000".equals(code)) {

                String tradeStatus = alipay_trade_query_response.getString("trade_status");
                //交易为成功状态
                if (null != tradeStatus && TradeStatusField.TRADE_SUCCESS.value().equals(tradeStatus)) {


                    payRecord.setOrderStatus("paid");
                    payRecord.setTradeId(jsonResult.getString(AlipayField.TRADE_NO.field()));
                    payRecord.setPayTime(jsonResult.getString(AlipayField.SEND_PAY_DATE.field()));
                    payRecord.setBuyerId(jsonResult.getString(AlipayField.BUYER_ID.field()));
                    payRecord.setOrderStatus(TradeStatusField.TRADE_SUCCESS.value());

                    payService.update(payRecord);

                }
            }

        }


    }

}
